package com.wnxy.sddfp.common.util;

import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.Map;

public class JwtTemplate {

    /**
     * 创建签名器
     */
    private JWTSigner jwtSigner() {
        // 创建密钥对工厂，加载证书文件，指定证书文件访问密码
        KeyStoreKeyFactory factory =
                new KeyStoreKeyFactory(new ClassPathResource("sdd.jks"),"123456".toCharArray());
        // 获取RSA加密的密钥对
        KeyPair keyPair = factory.getKeyPair("sdd");
        JWTSigner signer = JWTSignerUtil.createSigner("RSA",keyPair);
        return signer;
    }

    /**
     * 生成token
     */
    public String createToken(Map<String, Object> payload) {
        return JWTUtil.createToken(payload, jwtSigner());
    }

    /**
     * 校验token
     */
    public boolean verify(String token) {
        return JWTUtil.verify(token, jwtSigner());
    }

    /**
     * 解析token
     */
    public Object parseToken(String token,String key) {
        return JWTUtil.parseToken(token).getPayload(key);
    }
}
